#include "DXUT.h" // this include has to be included in the beginning of each source file for compiling

#include "./../Headers/anflex_file_reader.h"

namespace AnflexUtil {

	void readAnflexFile( const string &filename ){

		FILE *ptr_file = NULL;

		if( ! file_open( filename + ".DEF", ptr_file, "r" ) )
			throw Exception( "Couldn't open the given file" );

		int qtt_points = 0;
		fscanf_s( ptr_file, "%d", &qtt_points );

		COLOR_POS temp_color;

		SIMPLE_CONTROL_POINT temp_point;
		MAT_COLOR_POS *matrix_position = new MAT_COLOR_POS( (usint) qtt_points, 1 );
		const usint name_size = 16;
		char element_name[name_size];
		for( usint i = 0; i < qtt_points; ++i ){
			// ignore spaces and tabs
			fscanf_s( ptr_file, "%[^ ^\t]%f%f%f\n",
				&element_name, name_size,
				&temp_point.m_vPosition[X],
				&temp_point.m_vPosition[Y],
				&temp_point.m_vPosition[Z]
			);
			temp_point.index = i;
			control_point_list, temp_point;
			temp_color.pos[X] = temp_point.m_vPosition[X];	temp_color.pos[Y] = temp_point.m_vPosition[Y];	temp_color.pos[Z] = temp_point.m_vPosition[Z];
			matrix_position->setVal( 0, i, temp_color );
			//cout << "PT " << i << "\n Name: " << element_name << " ( " << x << ", " << y << ", " << z << " )" << endl;
		}
		tex_pos->setTexture( matrix_position );

		int begin_time, end_time;

		fscanf_s( ptr_file, "%d%d", &begin_time, &end_time );
		cout << "Begin " << begin_time << "\n End " << end_time << endl;

		end_time -= begin_time;
		float cur_time;
		MAT_COLOR_POS *matrix_offset = new MAT_COLOR_POS( (usint) qtt_points, (usint) end_time + 1 );
		for( usint i = 0; i <= end_time; ++i ){
			for( usint j = 0; j < qtt_points; ++j ){
				fscanf_s( ptr_file, "%f%f%f%f\n",
					&temp_color.pos[X],
					&temp_color.pos[Y],
					&temp_color.pos[Z],
					&cur_time );
				matrix_offset->setVal( i, j, temp_color + matrix_position->getVal(0,j) );
				//cout << "Desl " << j << "\n ( " << x << ", " << y << ", " << z << " )" << endl;
			}
			//cout << "Time " << i << "\n At: " << cur_time << endl;
		}

		// time slider
		time_initial = (float) begin_time; time_final = (float) begin_time + end_time;

		tex_offset->setTexture( matrix_offset );
		if( ! file_close( ptr_file ) )
			throw Exception( "Couldn't close the given file" );

	};

};
